#include "StoreCheck.h"
#include "ui_StoreCheck.h"

StoreCheck::StoreCheck(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::StoreCheck)
{
    StoreCheck::initMenu();
}

StoreCheck::StoreCheck(const User &operatorInfo, QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::StoreCheck),m_operatorInfo(operatorInfo)
{
    StoreCheck::initMenu();
}

StoreCheck::~StoreCheck()
{
    delete ui;
}

void StoreCheck::initMenu(void)
{
    ui->setupUi(this);

    connect(ui->tbtn_storeCheck,&QPushButton::clicked,this,[this](){
        ui->stackedWidget->setCurrentWidget(ui->page_storeCheck);
    });
    connect(ui->tbtn_anomalyRecord,&QPushButton::clicked,this,[this](){
        ui->stackedWidget->setCurrentWidget(ui->page_anomalyRecord);
    });
    connect(ui->tbtn_exit,&QPushButton::clicked,this,&StoreCheck::close);

    ui->tw_partCheck->setColumnCount(5);
    QStringList headers;
    headers << "ID" << "姓名" << "分数" << "操作" << "选择";
    ui->tw_partCheck->setHorizontalHeaderLabels(headers);

    // 设置表格充满父窗口
    ui->tw_partCheck->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->tw_partCheck->verticalHeader()->setVisible(false); // 隐藏行号

    StoreCheck::refresh_TW_PartCheckRecored();
}

void StoreCheck::refresh_TW_PartCheckRecored()
{
    ui->tw_partCheck->setRowCount(3);

    for(int i =0;i<3;i++)
    {
        ui->tw_partCheck->setItem(i, 0, new QTableWidgetItem(QString::number(i+1000)));
        ui->tw_partCheck->setItem(i, 1, new QTableWidgetItem(QString("%1").arg('A'+i)));
        ui->tw_partCheck->setItem(i, 2, new QTableWidgetItem(QString::number(66*i)));

        QPushButton* tmpOperateButton = new QPushButton("自定义操作");
        ui->tw_partCheck->setCellWidget(i,3,tmpOperateButton);

        connect(tmpOperateButton,&QPushButton::clicked,this,&StoreCheck::onOperateButtonClicked);

        QCheckBox* tmpSelectBox = new QCheckBox();
        QWidget *checkBoxWidget = new QWidget();
        QHBoxLayout *checkBoxLayout = new QHBoxLayout(checkBoxWidget);
        checkBoxLayout->addWidget(tmpSelectBox);
        checkBoxLayout->setAlignment(Qt::AlignCenter);
        checkBoxLayout->setContentsMargins(0, 0, 0, 0);
        ui->tw_partCheck->setCellWidget(i,4,checkBoxWidget);
    }
}

void StoreCheck::onOperateButtonClicked()
{
    // 使用 sender() 获取发出信号的对象
    QPushButton *button = qobject_cast<QPushButton*>(sender());

    // 确保转换成功，避免空指针
    if (button) {
        // 通过 findChild() 或者其他方式找到按钮所在的单元格或行
        // 最直接的方法是遍历表格，找到是哪个按钮
        for (int i = 0; i < ui->tw_partCheck->rowCount(); ++i) {
            if (ui->tw_partCheck->cellWidget(i, 3) == button) {
                qDebug() << "点击了第" << i+1 << "行的操作按钮";

                // 获取该行的数据
                QTableWidgetItem *nameItem = ui->tw_partCheck->item(i, 1);
                if (nameItem) {
                    qDebug() << "该行数据为: 姓名=" << nameItem->text();
                }
                return; // 找到后立即返回，避免不必要的循环
            }
        }
    }
}

